<?php

/**
 * Pes for PHP 5.3+
 *
 * Copyright (c) 2013 phpeskill.com (http://www.pescms.com)
 *
 * For the full copyright and license information, please view
 * the file LICENSE.md that was distributed with this source code.
 */

namespace App\Admin;

use Core\Db\Db as Db;
use Model\Admin\OptionModel as OptionModel;
use Model\Admin\ModelModel as ModelModel;
use Model\Admin\FieldModel as FieldModel;

/**
 * PES模型管理
 * @author LazyPHP
 * @version 1.0
 */
class Model extends Common {

    /**
     * 列出所有模型
     */
    public function index() {
        $db = $this->db('model');
        $list = $db->select();
        $this->assign('list', $list);
        $this->display();
    }

    /**
     * 创建模型
     */
    public function addModel() {
        $data = self::ajaxMethod($_POST['key'], $_POST['value']);
        self::ajaxExistParam('model_name', $data, '请输入模型名称');
        self::ajaxExistParam('name', $data, '请输入中文名称');
        $db = $this->db('model');

        //入库
        $data['model_name'] = ucwords($data['model_name']);
        $data['status'] = '1';
        $db->startTrans();
        $addModel = $db->add($data);
        if ($addModel == false) {
            $db->rollBack();
            $this->error('添加模型失败');
        }

        //添加字段
        $db->tableName('field');
        $field[1]['model_id'] = $addModel;
        $field[1]['field_name'] = 'listsort';
        $field[1]['name'] = '排序';
        $field[1]['type'] = 'text';
        $field[1]['option'] = '';
        $field[1]['default'] = '';
        $field[1]['required'] = '0';
        $field[1]['htmlentities'] = '0';
        $field[1]['listsort'] = '98';
        $field[1]['status'] = '1';
        $field[2]['model_id'] = $addModel;
        $field[2]['field_name'] = 'status';
        $field[2]['name'] = '状态';
        $field[2]['type'] = 'radio';
        $field[2]['option'] = '["\\u7981\\u7528","\\u542f\\u7528"]';
        $field[2]['default'] = '1';
        $field[2]['required'] = '1';
        $field[2]['htmlentities'] = '0';
        $field[2]['listsort'] = '100';
        $field[2]['status'] = '1';
        $field[3]['model_id'] = $addModel;
        $field[3]['field_name'] = 'createtime';
        $field[3]['name'] = '发布时间';
        $field[3]['type'] = 'date';
        $field[3]['option'] = '';
        $field[3]['default'] = '';
        $field[3]['required'] = '0';
        $field[3]['htmlentities'] = '0';
        $field[3]['listsort'] = '99';
        $field[3]['status'] = '1';
        $addField = $db->addAll($field);
        if ($addField == false) {
            $db->rollBack();
            $this->error('添加字段失败');
        }

        //添加菜单
        $db->tableName('menu');
        $menu['value'] = $data['model_name'];
        $menu['name'] = $data['name'];
        $menu['parent'] = 'Model';
        $menu['pid'] = 9;
        
        $menu['url'] = $this->url("Admin-{$data['model_name']}-index");
        $addMenu = $db->add($menu);
        if ($addMenu == false) {
            $db->rollBack();
            $this->error('添加模型菜单失败');
        }

        //创建表
        $table['name'] = 'pes_' . strtolower($data['model_name']);
        $db->query('CREATE TABLE IF NOT EXISTS ' . $table['name'] . ' (`id` int(11) NOT NULL AUTO_INCREMENT, `listsort` int(11) NOT NULL,`status` tinyint(4) NOT NULL, `lang` tinyint(4) NOT NULL, `url` VARCHAR( 255 ) NOT NULL, `createtime` int(11) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;');
        $exitTable = $db->query('show tables like :name;', $table);
        if ($exitTable == FALSE) {
            $db->rollBack();
            $this->error('创建模型表失败');
        }

        $this->success('创建模型成功');
    }

    /**
     * 删除模型
     */
    public function deleteModel() {
        $model_id = $this->is_g('model_id', '请选择您要删除的模型');
        $db = $this->db('model');
        $model['id'] = $model_id;
        $getModelInfo = $db->field('id, model_name')->where('id = :id')->find($model);
        //启用事务
        $db->startTrans();
        //删除模型
        $deleteModel = $db->where('id = :id')->delete($model);
        if ($deleteModel == false) {
            $db->rollBack();
            $this->error('删除模型失败!');
        }
        //删除对应模型的字段
        $db->tableName('field');
        $deleteField = $db->where("model_id = {$getModelInfo['id']}")->delete();
        if ($deleteField == false) {
            $db->rollBack();
            $this->error('删除对应模型的字段失败');
        }
        //删除菜单
        $db->tableName('menu');
        $deleteMenu = $db->where("value = '{$getModelInfo['model_name']}'")->delete();
        if ($deleteMenu == false) {
            $db->rollBack();
            $this->error('删除对应模型的菜单失败');
        }
        //删除模型表
        $result = $db->alter("DROP TABLE  `pes_" . strtolower($getModelInfo['model_name']) . "`");
        if ($result == false) {
            $db->rollBack();
            $this->error('删除模型表出错');
        } else {
            $this->success('成功删除模型!', '/?g=Admin&m=Model&a=index');
        }
    }

    /**
     * 列出对应模型的字段
     */
    public function field() {
        $param['model_id'] = $this->is_g('model_id', '请选择您要查看的字段模型');
        $this->existModel($param['model_id']);

        $db = $this->db('field');
        $lisr = $db->where('model_id = :model_id')->order('listsort asc, id desc')->select($param);
        $this->assign('list', $lisr);
        $this->display();
    }

    /**
     * 初始化添加字段
     */
    public function addField() {
        $model_id = $this->is_g('model_id', '请选择您要添加字段的模型');
        $this->existModel($model_id);

        $formtype = OptionModel::formtype();
        $this->assign('formtype', $formtype);
        $this->assign('url', "/?g=Admin&m=Model&a=addField&model_id={$model_id}");
        $this->assign('actionUrl', "/?g=Admin&m=Model&a=insertField&model_id={$model_id}");
        $this->display('field_add');
    }

    /**
     * 插入字段
     */
    public function insertField() {
        $model_id = $this->is_g('model_id', '请选择您要添加字段的模型');
        //获取模型信息
        $modelInfo = $this->existModel($model_id);

        //检查提交类型是否合法
        $optionResult = OptionModel::getOption('formtype', 'option_name');
        $formType = json_decode($optionResult['value'], true);
        if (!in_array($_POST['type'], array_flip($formType))) {
            $this->error('请勿提交不存在的字段类型');
        }
        //处理POST数据
        $data['model_id'] = $model_id;
        foreach ($_POST as $key => $value) {
            $data[$key] = trim($value);
        }
        //拆分文本框内容
        $splitNewline = explode("\n", $_POST['option']);
        foreach ($splitNewline as $value) {
            $splitOption[] = explode("|", $value);
            foreach ($splitOption as $key => $value) {
                $option[$value[0]] = $value[1];
            }
        }
        if (!is_array($option)) {
            $this->error('拆分文本框出错');
        }
        $data['option'] = json_encode($option);

        //加入字段表
        $db = $this->db('field');
        $addField = $db->add($data);
        if ($addField == false) {
            $this->error('添加字段到字段表时出错');
        }

        //将字段增加到表结构
        switch ($data['type']) {
            case 'category':
            case 'select':
            case 'radio':
                $field_type = 'INT';
                break;

            case 'text':
            case 'checkbox':
            case 'thumb':
                $field_type = 'VARCHAR( 255 ) ';
                break;

            case 'textarea':
            case 'editor':
            case 'img':
            case 'file':
                $field_type = 'TEXT';
                break;

            default:
                //此处应该存在一个删除刚才插入值的代码
                $this->error('错误的字段类型');
                break;
        }
        $tableName = strtolower($modelInfo['model_name']);
        $addStructure = $db->alter("ALTER TABLE  `pes_{$tableName}` ADD  `{$data['field_name']}` {$field_type} NOT NULL");
        if ($addStructure == FALSE) {
            $this->error("{$modelInfo['model_name']}模型插入结构字段时出错!");
        }
        $this->success("{$modelInfo['model_name']}模型成功添加字段!", "/?g=Admin&m=Model&a=field&model_id={$model_id}");
    }

    /**
     * 初始化字段编辑页面
     */
    public function editField() {
        $model_id = $this->is_g('model_id', '请选择您要编辑字段的模型');
        $id = $this->is_g('id', '请选择您要编辑的字段');
        $modelInfo = $this->existModel($model_id);
        
        $db = $this->db('field pf');
        $field['id'] = $id;
        $field['model_id'] = $model_id;
        $getFieldAttribute = $db->field('pf.*')->join('pes_model pm on pm.id = pf.model_id')->where('pf.id = :id and pf.model_id = :model_id')->find($field);
        if ($getFieldAttribute == false) {
            $this->error('不存在此字段');
        }

        $formtype = OptionModel::formtype($getFieldAttribute['type']);
        $this->assign('formtype', $formtype);
        foreach($getFieldAttribute as $key => $value){
            $this->assign($key, $value);
        }
        
        //拆解选项属性
        $option = '';
        foreach(json_decode($getFieldAttribute['option'], true) as $key => $value){
            if(!empty($value) && !empty($key)){
                $option .= "{$key}|$value";
            }
        }
        $this->assign('option', $option);
        
        $this->assign('url', "/?g=Admin&m=Model&a=editField&model_id={$model_id}&id={$id}");
        $this->assign('actionUrl', "/?g=Admin&m=Model&a=updateField&model_id={$model_id}&id={$id}");
        $this->display('field_add');
    }
    
    /**
     * 更新字段
     */
    public function updateField() {
        $model_id = $this->is_g('model_id', '请选择您要编辑字段的模型');
        $id = $this->is_g('id', '请选择您要编辑的字段');
        $modelInfo = $this->existModel($model_id);
        
        $db = $this->db('field pf');
        $field['id'] = $id;
        $field['model_id'] = $model_id;
        $getFieldAttribute = $db->field('*')->join('pes_model pm on pm.id = pf.model_id')->where('pf.id = :id and pf.model_id = :model_id')->find($field);
        if ($getFieldAttribute == false) {
            $this->error('不存在此字段');
        }
        
        //处理POST数据
        $data['model_id'] = $model_id;
        $data['id'] = $id;
        foreach ($_POST as $key => $value) {
            $data[$key] = trim($value);
        }
        //拆分文本框内容
        $splitNewline = explode("\n", $_POST['option']);
        foreach ($splitNewline as $value) {
            $splitOption[] = explode("|", $value);
            foreach ($splitOption as $key => $value) {
                $option[$value[0]] = $value[1];
            }
        }
        if (!is_array($option)) {
            $this->error('拆分文本框出错');
        }
        $data['option'] = json_encode($option);
        
        //更新字段
        $db = $this->db('field');
        $updateField = $db->where("id = {$id} and model_id = {$model_id}")->save($data);
        if ($updateField == false) {
            $this->error('更新字段内容出错');
        }
        $this->success('成功更新字段内容', "/?g=Admin&m=Model&a=field&model_id={$model_id}");
    }

    /**
     * 删除指定模型的字段
     */
    public function deleteField() {
        $model_id = $this->is_g('model_id', '请选择您要删除的模型字段');
        $id = $this->is_g('id', '请选择您要删除的字段');

        $this->existModel($model_id);

        $db = $this->db('field pf');
        $field['id'] = $id;
        $field['model_id'] = $model_id;
        $getFieldAttribute = $db->field('pf.field_name, pm.model_name')->join('pes_model pm on pm.id = pf.model_id')->where('pf.id = :id and pf.model_id = :model_id')->find($field);
        if ($getFieldAttribute == false) {
            $this->error('不存在此字段');
        }

        //Mysql删除不支持别名~囧
        $db->tableName('field');
        $deleteField = $db->where('id = :id and model_id = :model_id')->delete($field);
        if ($deleteField == false) {
            $this->error('删除字段失败');
        }

        //删除字段
        $result = $db->alter("ALTER TABLE `pes_" . strtolower($getFieldAttribute['model_name']) . "` DROP `{$getFieldAttribute['field_name']}`;");
        if ($result == false) {
            $this->error('删除模型上的字段出错');
        } else {
            $this->success('成功删除字段');
        }
    }

}
